﻿using System.Collections.ObjectModel;
using System.IO;
using System;
using System.Windows.Input;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Win32;
using Autorent.Desktop.Main;
using Autorent.Desktop.Model.AutorentMngrServiceReference;
using Autorent.Desktop.Model.Services;
using Autorent.Desktop.Modules.Autoes.Services;
using Autorent.Desktop.Modules.Autoes.Views;
using Autorent.Desktop.Modules.Events;

namespace Autorent.Desktop.Modules.Autoes.ViewModels
{
    public class UpdateAutoViewModel
    {
        #region Public Properties

        public UpdateAutoView View { get; set; }

        public Auto Auto { get; set; }

        public ObservableCollection<AutoClass> ClassAuto
        {
            get
            {
                return _repositoryAutoClass.GetAutoClasses();
            }
        }

        #endregion

        #region Constructors

        //constructor for editing car, with car object as a parameter
        public UpdateAutoViewModel(UpdateAutoView view, IAutoesRepository autoRepository,
            IAutoClassesRepository classRepository, IEventAggregator eventAggregator, IRegionManager regionManager, Auto auto)
        {
            this.View = view;
            this.View.Model = this;

            this.Auto = auto;

            _repositoryAuto = autoRepository;
            _repositoryAutoClass = classRepository;

            _eventAggregator = eventAggregator;
            _regionManager = regionManager;
        }

        #endregion

        #region Commands

        public ICommand AddAuto
        {
            get
            {
                return new RelayCommand(param => addAuto());
            }
        }

        public ICommand Cancel
        {
            get
            {
                return new RelayCommand(param => cancel());
            }
        }

        public ICommand SelectPhoto
        {
            get
            {
                return new RelayCommand(param => selectPhoto());
            }
        }

        #endregion

        #region Private Variables

        private readonly IAutoesRepository _repositoryAuto;
        private readonly IAutoClassesRepository _repositoryAutoClass;
        private readonly IEventAggregator _eventAggregator;
        private readonly IRegionManager _regionManager;
        private readonly bool _isEdit = false;

        #endregion

        #region Private Methods

        private void addAuto()
        {
            //add auto_class_id property to Auto object

            this.Auto.AutoClass_ID = this.Auto.AutoClass.AutoClass_ID;

            _repositoryAuto.UpdateAuto(this.Auto);
 
            _eventAggregator.GetEvent<CollectionChangedEvent>().Publish("Autoes");
            _regionManager.Regions["DetailsRegion"].Remove(View);
        }

        private void cancel()
        {
            _regionManager.Regions["DetailsRegion"].Remove(View);
        }

        private void selectPhoto()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            if (openFileDialog.ShowDialog() == true)
            {
                FileStream fs = new FileStream(openFileDialog.FileName, FileMode.Open);
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, (int)fs.Length);
                Auto.AutoPhoto = ImageResize(fs, 100);
            }
        }


        #region resizing helpers

        //main resizing method (using System.Drawing.Thumbnail class)
        private byte[] ImageResize(FileStream fs, int newWidth)
        {
            //resize image to appropriate size
            System.Drawing.Image.GetThumbnailImageAbort myHandler = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

            using (System.Drawing.Image sourceImg = System.Drawing.Image.FromStream(fs))
            {
                double koefOfCompression = (double)(sourceImg.Width / newWidth);
                int newHeight = (int)(sourceImg.Height / koefOfCompression);
                using (System.Drawing.Image thumbnailImage = sourceImg.GetThumbnailImage(newWidth, newHeight, myHandler, IntPtr.Zero))
                {
                    MemoryStream stream = new MemoryStream();
                    try
                    {
                        thumbnailImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        stream.Position = 0;
                        return stream.ToArray();
                    }
                    catch (Exception ex)
                    {
                        sourceImg.Dispose();
                        stream.Dispose();
                        throw new Autorent.Desktop.Model.AutorentModelException("Error occured while converting image", ex.InnerException);
                    }
                    finally
                    {
                        sourceImg.Dispose();
                        fs.Close();
                        fs.Dispose();
                    }
                }
            }
        }


        // create some ununderstandable shit for thumbnail abort handler
        public bool ThumbnailCallback()
        {
            return false;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        #endregion

        #endregion
    }
}
